package com.simple.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

/**
 * @author yasud
 * @date 2021年11月06日 18:09
 * @description
 */
public class Jsons {

    /**
     * 转换为对象
     *
     * @param json
     * @param rClass
     * @param <R>
     * @return
     */
    public static <R> R toObject(String json, Class<R> rClass) {
        try {
            ObjectMapper objectMapper = SpringUtil.getApplicationContext().getBean(ObjectMapper.class);
            R r = objectMapper.readValue(json, rClass);
            return r;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 转换为json
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            ObjectMapper objectMapper = SpringUtil.getApplicationContext().getBean(ObjectMapper.class);
            return objectMapper.writeValueAsString(obj);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
